<template>
  <div class="customer-group-container">
    <el-card class="page-container">
      <!-- 页面头部 -->
      <template #header>
        <div class="page-header">
          <h2 class="page-title">
            <el-icon>
              <User />
            </el-icon>
            客群库管理
          </h2>
          <el-button type="primary" @click="handleAdd" :icon="Plus">
            新增客群库
          </el-button>

        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-section flex align-center">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="客群库名称">
            <el-input v-model="searchForm.name" placeholder="请输入客群库名称" clearable style="width: 200px"
              @keyup.enter="handleSearch" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleH5Link" :loading="h5LinkLoading">
              <el-icon>
                <Link />
              </el-icon>
              H5链接
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 配置数量 -->
        <div class="config-stats-container">
          <div class="config-stat-item">
            <div class="config-stat-content">
              <div class="config-stat-label">客户群数</div>
              <div class="config-stat-value">
                <span class="current-count">{{ vdata.audience_num }}</span>
                <span class="separator">/</span>
                <span class="total-count">{{ vdata.audience_num_limit === 0 ? '无限制' : vdata.audience_num_limit }}</span>
              </div>
            </div>
          </div>

          <!-- <div class="config-stat-item">
            <div class="config-stat-content">
              <div class="config-stat-label">可创建客户群数</div>
              <div class="config-stat-value">
                <span class="current-count">0</span>
                <span class="separator">/</span>
                <span class="total-count">100</span>
              </div>
            </div>
          </div> -->
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table :data="tableData" v-loading="loading" style="width: 100%" border stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="客群库名称" min-width="150" />
          <el-table-column prop="type_words" label="分类" min-width="150" />
          <el-table-column prop="people_num" label="总人数" width="100">
            <template #default="{ row }">
              <el-tag type="info">{{ row.people_num }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tag" label="标签" min-width="200">
            <template #default="{ row }">
              <el-tag v-for="tag in row.tag" :key="tag" size="small" style="margin-right: 5px">
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180" />
          <el-table-column prop="updated_at" label="更新时间" width="180" />
          <el-table-column label="操作" width="320" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleViewContacts(row)">
                <el-icon>
                  <View />
                </el-icon>
                详情
              </el-button>
              <el-button type="success" size="small" @click="handleShare(row)">
                <el-icon>
                  <Share />
                </el-icon>
                分享
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑弹框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="客群库名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客群库名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-radio v-model="form.type" label="1">微信号</el-radio>
          <el-radio v-model="form.type" label="2">手机号</el-radio>
        </el-form-item>

        <!-- 账号选择 - 仅在选择手机号时显示 -->
        <el-form-item v-if="form.type === '2'" label="选择账号" prop="account_ids">
          <el-select v-model="form.account_ids" multiple filterable remote :remote-method="debouncedAccountSearch"
            placeholder="请输入账号ID搜索或选择账号" style="width: 100%" :loading="accountLoading" :disabled="isEdit"
            :reserve-keyword="true" value-key="account_id" :multiple-limit="5"
            @visible-change="handleAccountSelectVisible">
            <el-option v-for="account in accountOptions" :key="account.account_id"
              :label="`${account.account_name} (${account.account_id})`" :value="account.account_id">
              <span style="float: left">{{ account.account_name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ account.account_id }}</span>
            </el-option>
          </el-select>
          <div class="form-tip">
            <span style="font-size: 12px; color: #999;">
              输入账号ID进行搜索（至少2个字符），或直接选择账号，可多选。注意:账号类型只能是ACCOUNT_ROLE_TYPE_ADVERTISER
            </span>
            <div v-if="isEdit" style="margin-top: 4px;">
              <span style="font-size: 12px; color: #e6a23c;">
                ⚠️ 编辑模式下账号选择不可修改
              </span>
            </div>
            <div v-if="accountOptions.length > 0" style="margin-top: 4px;">
              <span style="font-size: 12px; color: #409eff;">
                找到 {{ accountOptions.length }} 个账号
              </span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-tag v-for="(tag, index) in form.tags" :key="index" closable @close="removeTag(index)"
            style="margin-right: 8px; margin-bottom: 4px;">
            {{ tag }}
          </el-tag>
          <el-input v-if="tagInputVisible" ref="tagInputRef" v-model="tagInputValue" size="small"
            style="width: 120px; margin-right: 8px;" @keyup.enter="addTag" @blur="addTag" placeholder="输入标签" />
          <el-button v-else size="small" @click="showTagInput">
            + 添加标签
          </el-button>
          <div class="tag-tip">
            <span style="font-size: 12px; color: #999;">
              点击"添加标签"或按回车键添加新标签，点击标签右侧×号删除
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 分享弹框 -->
    <el-dialog v-model="shareDialogVisible" title="分享客群库" width="500px">
      <div v-loading="shareLoading" class="share-content">
        <div v-if="shareUrl" class="share-section">
          <h4>分享链接</h4>
          <div class="link-section">
            <el-input v-model="shareUrl" readonly class="share-input">
              <template #suffix>
                <el-button type="primary" size="small" @click="copyShareLink" :loading="shareLoading">
                  复制
                </el-button>
              </template>
            </el-input>
          </div>


        </div>

        <div v-else class="loading-section">
          <p>正在生成分享链接...</p>
        </div>
      </div>
    </el-dialog>

    <!-- H5链接弹框 -->
    <el-dialog v-model="h5LinkDialogVisible" title="H5链接" width="500px">
      <div v-loading="h5LinkLoading" class="share-content">
        <div v-if="h5LinkUrl" class="share-section">
          <h4>H5链接</h4>
          <div class="link-section">
            <el-input v-model="h5LinkUrl" readonly class="share-input">
              <template #suffix>
                <el-button type="primary" size="small" @click="copyH5Link" :loading="h5LinkLoading">
                  复制
                </el-button>
              </template>
            </el-input>
          </div>
        </div>

        <div v-else class="loading-section">
          <p>正在生成H5链接...</p>
        </div>
      </div>
    </el-dialog>

    <!-- 群发弹框 -->
    <BulkSendDialog v-model:visible="bulkSendVisible" :customer-groups="tableData" :total-contacts="totalContacts"
      @confirm="handleBulkSendConfirm" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, ElLoading } from 'element-plus'
import {
  User, Plus, Search, Refresh, View, Edit, Delete, Share, ChatLineSquare, Link
} from '@element-plus/icons-vue'
import {
  getCustomerGroupList,
  addCustomerGroup,
  updateCustomerGroup,
  deleteCustomerGroup,
  getShareLink,
  getLibraryShareLink,
  getCount,
  type CustomerGroup
} from '@/api/customer-group'
import BulkSendDialog from '@/components/BulkSendDialog.vue'

// 导入账号列表API
import { apiGetAccounts } from '@/api/tencent_ad_creativity'

// 账号类型定义
interface Account {
  account_id: string | number
  account_name: string
  account_role_type?: string
}

const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref<CustomerGroup[]>([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增客群库')
const isEdit = ref(false)
const currentId = ref<number | null>(null)

//限制数量
const vdata = reactive({
  audience_num: 0,
  audience_num_limit: 0,
})


// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 表单
const formRef = ref<FormInstance>()
const tagInputRef = ref<HTMLInputElement>()
const form = reactive({
  name: '',
  type: '1',
  tags: [] as string[],
  account_ids: [] as (string | number)[]
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入客群库名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  account_ids: [
    {
      required: true,
      message: '请选择至少一个账号',
      trigger: 'change',
      validator: (rule: any, value: any, callback: any) => {
        // 在编辑模式下不验证账号选择
        if (isEdit.value) {
          callback()
          return
        }

        if (form.type === '2' && (!value || value.length === 0)) {
          callback(new Error('请选择至少一个账号'))
        } else {
          callback()
        }
      }
    }
  ],
  tags: [
    { required: true, message: '请选择至少一个标签', trigger: 'change' }
  ]
}

// 标签输入相关
const tagInputVisible = ref(false)
const tagInputValue = ref('')

// 分享功能
const shareDialogVisible = ref(false)
const shareLoading = ref(false)
const shareUrl = ref('')
const currentShareGroup = ref<CustomerGroup | null>(null)
const qrCodeRef = ref<HTMLElement>()

// H5链接功能
const h5LinkDialogVisible = ref(false)
const h5LinkLoading = ref(false)
const h5LinkUrl = ref('')
const currentH5LinkGroup = ref<CustomerGroup | null>(null)

// 群发相关
const bulkSendVisible = ref(false)
const totalContacts = ref(0)

// 账号选择相关
const accountLoading = ref(false)
const accountOptions = ref<Account[]>([])
const isRequestCanceled = ref(false)

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: number
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      func.apply(null, args)
    }, delay)
  }
}

// 使用防抖处理的搜索函数
const debouncedAccountSearch = debounce((query: string) => {
  handleAccountSearch(query)
}, 1000)

// 根据账号ID获取账号信息
const getAccountInfoByIds = async (accountIds: (string | number)[]) => {
  if (!accountIds || accountIds.length === 0) {
    accountOptions.value = []
    return
  }

  try {
    accountLoading.value = true
    // 获取所有账号列表
    const params = {
      account_role_type: "ACCOUNT_ROLE_TYPE_ADVERTISER",
      page_size: 999
    }

    const response = await apiGetAccounts(params)

    console.log('接口返回的完整数据:', response)
    console.log('要匹配的账号ID:', accountIds)
    console.log('账号ID类型:', accountIds.map(id => typeof id))

    if (response && response.list) {
      console.log('接口返回的账号列表:', response.list)
      console.log('第一个账号的数据结构:', response.list[0])

      // 将账号ID转换为字符串类型进行比较
      const accountIdStrings = accountIds.map(id => String(id))
      console.log('转换后的账号ID字符串:', accountIdStrings)

      // 过滤出匹配的账号 - 匹配所有在accountIdStrings中的账号
      const matchedAccounts = response.list.filter((account: Account) => {
        const accountIdStr = String(account.account_id)
        const isMatched = accountIdStrings.includes(accountIdStr)
        console.log('比较:', accountIdStr, '是否在', accountIdStrings, '中:', isMatched)
        return isMatched
      })

      console.log('匹配到的账号:', matchedAccounts)
      console.log('匹配到的账号数量:', matchedAccounts.length)
      console.log('期望匹配的账号数量:', accountIdStrings.length)

      // 检查是否所有期望的账号都被找到了
      const matchedIds = matchedAccounts.map((account: Account) => String(account.account_id))
      const missingIds = accountIdStrings.filter(id => !matchedIds.includes(id))

      if (missingIds.length > 0) {
        console.warn('未找到的账号ID:', missingIds)
      } else {
        console.log('所有期望的账号都已找到')
      }

      // 更新账号选项，确保选中的账号显示在列表中
      accountOptions.value = matchedAccounts
      console.log('更新后的accountOptions:', accountOptions.value)
      console.log('form.account_ids:', form.account_ids)

      // 强制更新DOM
      await nextTick()
      console.log('DOM更新后的accountOptions:', accountOptions.value)

      // 确保form.account_ids的类型与accountOptions中的account_id类型一致
      if (matchedAccounts.length > 0) {
        // 根据调试信息，accountOptions中的account_id是字符串类型，所以转换为字符串
        form.account_ids = accountIds.map(id => String(id))

        console.log('类型转换后的form.account_ids:', form.account_ids)
        console.log('转换后的类型:', form.account_ids.map(id => typeof id))
      }
    } else {
      accountOptions.value = []
    }
  } catch (error: any) {
    console.error('获取账号信息失败:', error)

    // 检查是否是取消请求的错误
    if (error && (error.code === 'ERR_CANCELED' || error.name === 'CanceledError' || error.message?.includes('cancel'))) {
      console.log('获取账号信息请求被取消（正常行为）')
      return
    }

    accountOptions.value = []
  } finally {
    accountLoading.value = false
  }
}

// 获取账号列表
const getAccountList = async () => {
  try {
    isRequestCanceled.value = false
    accountLoading.value = true
    const params = {
      account_role_type: "ACCOUNT_ROLE_TYPE_ADVERTISER",
      page_size: 999
    }

    const response = await apiGetAccounts(params)

    if (response && response.list) {
      accountOptions.value = response.list
    } else {
      accountOptions.value = []
    }
  } catch (error: any) {
    console.error('获取账号列表失败:', error)

    // 检查是否是取消请求的错误（这是正常行为，不需要显示错误）
    if (error && (error.code === 'ERR_CANCELED' || error.name === 'CanceledError' || error.message?.includes('cancel'))) {
      console.log('获取账号列表请求被取消（正常行为）')
      isRequestCanceled.value = true
      return
    }

    // 只有在非取消错误时才显示错误消息
    if (!isRequestCanceled.value) {
      ElMessage.error('获取账号列表失败')
    }
    accountOptions.value = []
  } finally {
    if (!isRequestCanceled.value) {
      accountLoading.value = false
    }
  }
}

// 处理账号搜索
const handleAccountSearch = async (query: string) => {
  // 如果搜索词为空，加载所有账号
  if (query === '') {
    await getAccountList()
    return
  }

  // 如果搜索词太短，不进行搜索
  if (query.length < 2) {
    accountOptions.value = []
    return
  }

  try {
    isRequestCanceled.value = false
    accountLoading.value = true
    const params = {
      account_role_type: "ACCOUNT_ROLE_TYPE_ADVERTISER",
      ad_account_id: query, // 使用ad_account_id字段进行搜索
      page_size: 999
    }

    const response = await apiGetAccounts(params)

    if (response && response.list) {
      accountOptions.value = response.list
    } else {
      accountOptions.value = []
    }
  } catch (error: any) {
    console.error('搜索账号失败:', error)

    // 检查是否是取消请求的错误（这是正常行为，不需要显示错误）
    if (error && (error.code === 'ERR_CANCELED' || error.name === 'CanceledError' || error.message?.includes('cancel'))) {
      console.log('搜索请求被取消（正常行为）')
      isRequestCanceled.value = true
      return
    }

    // 只有在非取消错误时才显示错误消息
    if (!isRequestCanceled.value) {
      ElMessage.error('搜索账号失败，请重试')
    }
    accountOptions.value = []
  } finally {
    if (!isRequestCanceled.value) {
      accountLoading.value = false
    }
  }
}

// 处理账号选择框显示/隐藏
const handleAccountSelectVisible = (visible: boolean) => {
  if (visible && accountOptions.value.length === 0) {
    getAccountList()
  }
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const params = {
      page_no: pagination.page,
      page_size: pagination.pageSize,
      title: searchForm.name || undefined
    }

    const response = await getCustomerGroupList(params)

    if (response.code === 1) {
      tableData.value = response.list || []
      pagination.total = response.count || 0
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取客群库列表失败:', error)
    ElMessage.error('获取数据失败，请重试')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  pagination.page = 1
  getList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增客群库'
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: CustomerGroup) => {
  console.log(row, 'row  row')
  console.log('row.costom:', row.costom)

  dialogTitle.value = '编辑客群库'
  isEdit.value = true
  currentId.value = row.id
  form.name = row.title
  form.type = String(row.type)
  form.tags = [...row.tag]

  // 处理costom数组中的account_id
  if (row.costom && Array.isArray(row.costom)) {
    console.log('costom数组:', row.costom)
    // 从costom数组中提取account_id
    const accountIds = row.costom
      .filter(item => item && item.account_id)
      .map(item => item.account_id)

    console.log('提取的账号ID:', accountIds)
    console.log('账号ID类型:', accountIds.map(id => typeof id))

    form.account_ids = accountIds

    // 如果是手机号类型，获取账号信息并显示中文名称
    if (form.type === '2' && accountIds.length > 0) {
      await getAccountInfoByIds(accountIds)
      // 类型转换会在getAccountInfoByIds函数中处理
    }
  } else if (row.account_ids) {
    // 兼容原有的account_ids字段
    console.log('使用account_ids字段:', row.account_ids)
    form.account_ids = Array.isArray(row.account_ids) ? row.account_ids : []

    // 如果是手机号类型，获取账号信息并显示中文名称
    if (form.type === '2' && form.account_ids.length > 0) {
      await getAccountInfoByIds(form.account_ids)
      // 类型转换会在getAccountInfoByIds函数中处理
    }
  } else {
    form.account_ids = []
  }

  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: CustomerGroup) => {
  let loadingInstance: any = null

  try {
    await ElMessageBox.confirm(
      `确定要删除客群库"${row.title}"吗？此操作将同时删除该客群库下的所有联系人数据。`,
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    // 创建全屏加载实例
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在删除客群库...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    const response = await deleteCustomerGroup(row.id)

    if (response.code === 1) {
      ElMessage.success('删除成功')
      getList()
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客群库失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  } finally {
    // 关闭全屏加载
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
}

// 查看联系人
const handleViewContacts = (row: CustomerGroup) => {
  router.push({
    path: '/customer-group/contacts',
    query: {
      groupId: row.id,
      groupName: row.title,
      type: row.type
    }
  })
}

// 分享
const handleShare = async (row: CustomerGroup) => {
  try {
    shareLoading.value = true
    shareDialogVisible.value = true
    currentShareGroup.value = row
    shareUrl.value = ''

    const response = await getShareLink(row.id)

    if (response.code === 1) {
      shareUrl.value = response.url || ''
    } else {
      throw new Error(response.message || '获取分享链接失败')
    }
  } catch (error) {
    console.error('获取分享链接失败:', error)
    ElMessage.error('获取分享链接失败，请重试')
    shareDialogVisible.value = false
  } finally {
    shareLoading.value = false
  }
}

// H5链接
const handleH5Link = async () => {
  try {
    h5LinkLoading.value = true
    h5LinkDialogVisible.value = true
    h5LinkUrl.value = ''


    const response = await getLibraryShareLink()
    console.log(response, 'response')
    if (response.url) {
      console.log(response, 'response')
      h5LinkUrl.value = response.url || ''
    } else {
      throw new Error(response.message || '获取H5链接失败')
    }
  } catch (error) {
    console.error('获取H5链接失败:', error)
    ElMessage.error('获取H5链接失败，请重试')
    h5LinkDialogVisible.value = false
  } finally {
    h5LinkLoading.value = false
  }
}

// 生成二维码
const generateQRCode = async () => {
  if (!qrCodeRef.value || !shareUrl.value) return

  try {
    // 清空之前的二维码
    qrCodeRef.value.innerHTML = ''

    // 创建二维码canvas
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    if (!ctx) return

    // 设置canvas尺寸
    canvas.width = 200
    canvas.height = 200

    // 简单的二维码占位符（实际项目中应该使用专业的二维码库）
    ctx.fillStyle = '#000000'
    ctx.fillRect(0, 0, 200, 200)

    ctx.fillStyle = '#ffffff'
    ctx.font = '12px Arial'
    ctx.textAlign = 'center'
    ctx.fillText('二维码', 100, 100)
    ctx.fillText('扫码访问', 100, 120)

    qrCodeRef.value.appendChild(canvas)

    // 实际项目中可以使用 qrcode 库：
    // import QRCode from 'qrcode'
    // QRCode.toCanvas(canvas, shareUrl.value, { width: 200 })

  } catch (error) {
    console.error('生成二维码失败:', error)
  }
}

// 复制链接
const copyShareLink = async () => {
  try {
    await navigator.clipboard.writeText(shareUrl.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = shareUrl.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('链接已复制到剪贴板')
  }
}

// 复制H5链接
const copyH5Link = async () => {
  try {
    await navigator.clipboard.writeText(h5LinkUrl.value)
    ElMessage.success('H5链接已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = h5LinkUrl.value
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('H5链接已复制到剪贴板')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  let loadingInstance: any = null

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    // 创建全屏加载实例
    loadingInstance = ElLoading.service({
      lock: true,
      text: isEdit.value ? '正在保存编辑...' : '正在创建客群库...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    submitLoading.value = true

    let data: any = {
      title: form.name.trim(),
      type: form.type,
      tag: form.tags,
    }

    // 只在新增模式下添加account_ids
    if (!isEdit.value && form.type === '2') {
      data.account_ids = form.account_ids
    }

    let response
    if (isEdit.value && currentId.value) {
      const editData = {
        id: currentId.value,
        type: form.type,
        title: form.name.trim(),
        tag: form.tags,
        // 编辑模式下不提交account_ids
      }
      response = await updateCustomerGroup(currentId.value, editData)
    } else {
      response = await addCustomerGroup(data)
    }

    if (response.code === 1) {
      ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitLoading.value = false
    // 关闭全屏加载
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
}

// 重置表单
const resetForm = () => {
  form.name = ''
  form.type = '1'
  form.tags = []
  form.account_ids = []
  formRef.value?.clearValidate()
}

// 弹框关闭处理
const handleDialogClose = () => {
  resetForm()
}

// 添加标签
const addTag = () => {
  const trimmedValue = tagInputValue.value.trim()
  if (trimmedValue !== '' && !form.tags.includes(trimmedValue)) {
    form.tags.push(trimmedValue)
  }
  tagInputValue.value = ''
  tagInputVisible.value = false
}

// 移除标签
const removeTag = (index: number) => {
  form.tags.splice(index, 1)
}

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

// 群发功能
const handleBulkSend = () => {
  // 计算总联系人数
  totalContacts.value = tableData.value.reduce((sum, group) => sum + group.people_num, 0)

  if (totalContacts.value === 0) {
    ElMessage.warning('暂无联系人，请先添加客群库和联系人')
    return
  }

  bulkSendVisible.value = true
}

// 处理群发确认
const handleBulkSendConfirm = async (sendData: any) => {
  try {
    console.log('群发数据:', sendData)

    // 这里应该调用群发API接口
    // const response = await sendBulkMessage(sendData)

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success(`群发任务已创建，预计发送给 ${sendData.estimatedCount} 人`)

    // 可以跳转到发送记录页面
    // router.push('/message/send-records')

  } catch (error) {
    console.error('群发失败:', error)
    ElMessage.error('群发失败，请重试')
  }
}

const getCountData = async () => {
  const res = await getCount()
  vdata.audience_num = res.audience_num
  vdata.audience_num_limit = res.audience_num_limit
}


// 页面初始化
onMounted(() => {
  getList()
  getCountData()
})

// 监听分类变化，重置账号选择
watch(() => form.type, (newType) => {
  // 在编辑模式下，如果切换到非手机号类型，不清除账号选择
  if (isEdit.value) {
    return
  }

  // 只在新增模式下清除账号选择
  if (newType !== '2') {
    form.account_ids = []
  }
})
</script>

<style scoped>
.customer-group-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-container {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.search-form {
  margin: 0;
  margin-top: 20px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .customer-group-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }

  :deep(.el-table) {
    font-size: 12px;
  }

  .pagination-section {
    justify-content: center;
  }
}

/* 标签输入样式 */
.tag-tip {
  margin-top: 4px;
}

.tag-tip span {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

:deep(.el-tag) {
  margin-right: 8px;
  margin-bottom: 4px;
}

:deep(.el-tag.el-tag--small) {
  height: 24px;
  padding: 0 8px;
  font-size: 12px;
  border-radius: 12px;
}

:deep(.el-tag .el-tag__close) {
  margin-left: 4px;
}

/* 分享弹框样式 */
.share-content {
  min-height: 200px;
}

.share-section h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.link-section {
  margin-bottom: 30px;
}

.share-input {
  width: 100%;
}

:deep(.share-input .el-input__suffix) {
  padding-right: 8px;
}

.qr-section {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.qr-code {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 200px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #f8f9fa;
}

.qr-code canvas {
  border-radius: 6px;
}

.loading-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px;
  color: #909399;
  font-size: 14px;
}

/* 账号选择相关样式 */
.form-tip {
  margin-top: 4px;
  line-height: 1.4;
}

:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-select-dropdown__item span) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>


<style scoped>
/* 配置统计样式 */
.config-stats-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.config-stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  transition: all 0.3s ease;
  min-width: 140px;
  height: 32px;
}

.config-stat-item:hover {
  background: #f1f5f9;
  border-color: #3b82f6;
}

.config-stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: white;
  background: linear-gradient(135deg, #10b981, #34d399);
  box-shadow: 0 3px 10px rgba(16, 185, 129, 0.3);
  flex-shrink: 0;
}

.config-stat-icon.available {
  background: linear-gradient(135deg, #3b82f6, #60a5fa);
  box-shadow: 0 3px 10px rgba(59, 130, 246, 0.3);
}

.config-stat-content {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-stat-label {
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.config-stat-value {
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.current-count {
  color: #10b981;
}

.separator {
  color: #9ca3af;
  font-weight: 500;
}

.total-count {
  color: #6b7280;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .config-stats-container {
    flex-direction: column;
    gap: 12px;
    margin-left: 0;
    margin-top: 12px;
  }

  .config-stat-item {
    min-width: auto;
    width: 100%;
  }
}
</style>